import http from '../../utils/request';

Page({
  data: {
    currentTab: 'work',
    inRange: true,
    currentTime: '',
    displayTime: '',
    cardType: '上班打卡',
    canPunch: false,
    currentBottomTab: 'punch',
    location: '上海市浦东新区科技园区',
    punchRecord: [],
    workStartTime: '09:00',
    workEndTime: '18:00',
    isWorkPunched: false, // 初始化状态为未打卡
    isOffDutyPunched: 0,
    circleStyle: 'disabled',
    pulseAnimation: '',
    pageOpacity: 0,
    pageScale: 0.95,
    loadingComplete: false,
    tipText: '',
  },
  paserData: [],
  isExits: false, // 是否存在今日打卡记录（从接口获取）
  recordDate: '',
  returnUrl: '', // 修复：添加逗号分隔属性

  onLoad(options) {
    // 从参数中获取返回路径（如果有）
    this.returnUrl = options.returnUrl || '';
    this.paserData = wx.getStorageSync('user');
    this.resetStatus();
    this.updateTime();

    // 页面加载时检查登录状态并获取打卡记录
    if (this.paserData && this.paserData.id) {
      const today = new Date().toISOString().split('T')[0];
      this.getIsRecord(today); // 初始化时获取打卡状态
    }

    // 页面加载动画
    setTimeout(() => {
      this.setData({
        pageOpacity: 1,
        pageScale: 1
      });
      
      setTimeout(() => {
        this.timeInterval = setInterval(() => {
          this.updateTime();
          this.checkCanPunch(); // 依赖初始化后的 isWorkPunched 状态
        }, 1000);
        this.setData({ loadingComplete: true });
      }, 500);
    }, 100);
  },

  onShow() {
    // 页面显示时重新获取用户数据（处理登录后返回的情况）
    this.paserData = wx.getStorageSync('user');
    if (this.paserData && this.paserData.id) {
      const today = new Date().toISOString().split('T')[0];
      this.getIsRecord(today);
    }
  },

  onUnload() {
    clearInterval(this.timeInterval);
  },

  updateTime() {
    const now = new Date();
    const fullTime = this.formatFullTime(now);
    const displayTime = this.formatDisplayTime(now);
    
    this.setData({
      currentTime: fullTime,
      displayTime: displayTime
    });
  },

  formatFullTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  formatDisplayTime(date) {
    const hour = date.getHours();
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    const period = hour >= 12 ? '下午' : '上午';
    const displayHour = hour % 12 === 0 ? 12 : hour % 12;
    return `${period} ${displayHour.toString().padStart(2, '0')}:${minute}:${second}`;
  },

  checkCanPunch() {
    const now = new Date();
    const [workStartH, workStartM] = this.data.workStartTime.split(':').map(Number);
    const [workEndH, workEndM] = this.data.workEndTime.split(':').map(Number);
    
    const workStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), workStartH, workStartM);
    const workEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), workEndH, workEndM);
    
    const isBeforeWork = now < workStart;
    const isAfterWork = now >= workEnd;

    let canPunch = false;
    let circleStyle = 'disabled';
    let cardType = '未打卡';
    let tipText = '';

    if (!this.data.isWorkPunched) {
      if (isBeforeWork || now <= workEnd) {
        circleStyle = 'on-duty';
        canPunch = true;
        cardType = '上班打卡';
        tipText = isBeforeWork 
          ? `距离上班时间还有：${this.calculateDiffMins(workStart, now)}分钟` 
          : '请尽快打上班卡';
      } else {
        tipText = '已错过上班打卡时间';
      }
    } else {
      circleStyle = 'off-duty';
      canPunch = true;
      cardType = '下班打卡';
      tipText = isAfterWork 
        ? '点击打卡下班（可多次打卡）' 
        : `距离下班时间还有：${this.calculateDiffMins(workEnd, now)}分钟`;
    }

    this.setData({ canPunch, circleStyle, cardType, tipText });
  },

  calculateDiffMins(target, now) {
    const diffMs = target - now;
    return Math.max(0, Math.floor(diffMs / 60000));
  },

  handlePunch() {
    if (!this.paserData || !this.paserData.id) {
      // 未登录时存储当前页面路径
      const currentPage = getCurrentPages().pop();
      const returnUrl = '/pages/clock/clock';
      wx.setStorageSync('returnUrl', returnUrl);
      
      return wx.showModal({
        title: '提示',
        content: '请先登录再打卡',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/login/login' });
          }
        }
      });
    }

    const today = new Date().toISOString().split('T')[0];
    this.recordDate = today;
    const _this = this;

    // 点击打卡时再次获取状态（避免初始化后数据变更）
    this.getIsRecord(today, (isExits) => {
      _this.isExits = isExits;
      _this.setData({ isWorkPunched: isExits });

      if (!_this.data.canPunch) {
        return wx.showToast({
          title: _this.data.tipText,
          icon: 'none',
          duration: 2000
        });
      }

      // 执行打卡动画和逻辑
      _this.setData({ circleStyle: _this.data.circleStyle + ' clicked' });

      setTimeout(() => {
        _this.setData({ circleStyle: _this.data.circleStyle.replace(' clicked', '') });
        
        const record = {
          type: isExits ? '下班打卡' : '上班打卡',
          time: _this.data.currentTime,
          location: _this.data.location,
          timestamp: Date.now()
        };

        if (isExits) {
          _this.handleOffDutyPunch(record, today);
        } else {
          _this.handleWorkPunch(record, today);
        }

        _this.checkCanPunch();
      }, 200);
    });
  },

  // 上班打卡处理
  handleWorkPunch(record, today) {
    if (this.data.isWorkPunched) {
      return wx.showToast({ title: '上班卡已打卡', icon: 'none' });
    }

    // 预留接口调用位置（实际需添加）
    http.post('/attendance/record', { 
      clockInTime: this.data.currentTime,
      userId: this.paserData.id,
      recordDate: this.recordDate,
     }).then(res => { 
       console.log("打卡成功");
      });

    this.setData({
      isWorkPunched: true,
      punchRecord: [...this.data.punchRecord, record],
      cardType: '下班打卡'
    });
    wx.showToast({ title: '上班打卡成功', icon: 'success' });
  },

  // 下班打卡处理
  handleOffDutyPunch(record, today) {
    // 预留接口调用位置（实际需添加）
    http.post('/attendance/record', { 
      clockOutTime: this.data.currentTime,
      userId: this.paserData.id,
      recordDate: this.recordDate,
     }).then(res => { 
       console.log("打卡成功");
      });

    this.setData({
      isOffDutyPunched: this.data.isOffDutyPunched + 1,
      punchRecord: [...this.data.punchRecord, record]
    });
    wx.showToast({ 
      title: `下班打卡成功（第${this.data.isOffDutyPunched + 1}次）`, 
      icon: 'success' 
    });
  },

  resetStatus() {
    this.setData({
      isWorkPunched: false,
      isOffDutyPunched: 0,
      punchRecord: [],
      circleStyle: 'disabled',
      pulseAnimation: '',
      cardType: '上班打卡',
      tipText: ''
    });
  },

  switchTab(e) {
    this.setData({ currentTab: e.currentTarget.dataset.tab });
  },

  switchBottomTab(e) {
    this.setData({ currentBottomTab: e.currentTarget.dataset.tab });
  },

  // 获取打卡记录（带回调函数，用于初始化和点击时获取状态）
  getIsRecord(today, callback = () => {}) {
    if (!this.paserData?.id) return callback(false); // 未登录直接返回未打卡

    http.get('/attendance/attendanceRecord', {
      userId: this.paserData.id,
      recordDate: today
    })
    .then(res => {
      console.log('打卡记录查询结果:', res);
      // 根据接口返回调整判断逻辑（假设 data=1 表示已打上班卡）
      const isExits = res.data === 1;
      this.isExits = isExits;
      this.setData({ isWorkPunched: isExits }); // 更新到 data
      callback(isExits); // 传递结果给调用方
    })
    .catch(err => {
      console.log('获取打卡记录失败:', err);
      this.setData({ isWorkPunched: false });
      callback(false);
    });
  },
});